import 'dart:async';

import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/ble/protocol_data_util.dart';
import 'package:ty_smart_watch/common/function_id.dart';
import 'package:ty_smart_watch/utils/Log.dart';
import 'package:ty_smart_watch/utils/weather_util.dart';

class ViewModel {
  ViewModel._internal();

  factory ViewModel() => _instance;
  static final ViewModel _instance = ViewModel._internal();

  ///向手表发送时间矫正
  static updateTime() {
    Log.d("updateTime");
    var now = DateTime.now();
    var timeStamp = now.millisecondsSinceEpoch;
    var data = BleUtil.makeWriteData(
        functionId: TIME_UPDATE, data: ProtocolDataUtil.instance!.updateTime(timeStamp));
    BleUtil.writeBleData("36:ED:EC:E5:E4:A3", data);
  }

  ///获取初始数据
  static getInitInfo(String id) {
    int index = 0;
    var now = DateTime.now();
    var timeStamp = now.millisecondsSinceEpoch;
    var list = [
      //更新时间
      BleUtil.makeWriteData(
          functionId: TIME_UPDATE, data: ProtocolDataUtil.instance!.updateTime(timeStamp)),
      //步数目标
      BleUtil.makeWriteData(functionId: STEP_TARGET),
      //获取实时数据
      BleUtil.makeWriteData(functionId: REAL_TIME_DATA),
      //获取运动数据
      BleUtil.makeWriteData(functionId: SPORT_RECORDER),
      //血氧信息
      BleUtil.makeWriteData(functionId: BLOOD_OXYGEN),
      //发送天气
      WeatherUtil.sendTodayWeatherToWatch(id),
      WeatherUtil.sendMoreWeatherToWatch(id),
    ];
    Timer(const Duration(milliseconds: 50), () {
      Log.d("手表连接成功后，向手表发送初始数据");
      Timer.periodic(const Duration(milliseconds: 50), (timer) {
        if (index < list.length) {
          var data = list[index];
          BleUtil.writeBleData(id, data);
          index++;
        } else {
          Log.d("数据发送完成");
          timer.cancel();
        }
      });
    });
  }
}
